import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:note/common/tools.dart';
import 'package:note/models/noteModel.dart';
import '../../routeConfig.dart';
import 'state.dart';

class HomePageLogic extends GetxController {
  final HomePageState state = HomePageState();

  void onAddNote() {
    Get.toNamed(
      RouteConfig.editNotePage,
    );
  }

  void onUploadMd() async {
    Toasts.showToast('请选择.md或.txt后缀的文件');
    FilePickerResult? result = await FilePicker.platform
        .pickFiles(type: FileType.custom, allowedExtensions: ['md', 'txt']);
    if (result == null) {
      Toasts.showToast('未选择文件');
      return;
    } else if (result.files.single.extension != 'md' &&
        result.files.single.extension != 'txt') {
      Toasts.showToast('错误：请选择.md或.txt后缀的文件');
      return;
    } else {
      PlatformFile file = result.files.single;
      String data = File(file.path ?? '').readAsStringSync();
      String title = file.name;
      if (file.extension == 'txt') {
        title = title.substring(0, title.length - 4);
      } else if (file.extension == 'md') {
        title = title.substring(0, title.length - 3);
      }
      Note note = Note(
          id: DateTime.now().toString(),
          createTime: DateTime.now(),
          editTime: DateTime.now(),
          title: title,
          data: data);
      Get.toNamed(RouteConfig.editNotePage, arguments: note);
    }
  }

  void onSearch() {
    Get.toNamed(RouteConfig.searchPage);
  }

  Widget? openDraw() {
    return Builder(
      builder: (context) => IconButton(
        icon: const Icon(
          Icons.menu,
        ),
        onPressed: () => Scaffold.of(context).openDrawer(),
      ),
    );
  }
}
